package com.ideabove.util.img;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import android.graphics.Bitmap;

public class LRUCache {
	private static final float mHashTableLoadFactor = 0.75f;
	private LinkedHashMap<String, Bitmap> mMap;
	private int mCacheSize;

	public LRUCache(int cacheSize)
	{
		this.mCacheSize = cacheSize;
		int hashTableCapacity = (int) Math.ceil(cacheSize / mHashTableLoadFactor) + 1;
		mMap = new LinkedHashMap<String, Bitmap> (hashTableCapacity, mHashTableLoadFactor, true)
				{
			private static final long serialVersionUID = 1;

			@Override
			protected boolean removeEldestEntry(Map.Entry<String, Bitmap>  eldest)
			{
				return size() > LRUCache.this.mCacheSize;
			}
				};
	}

	public synchronized boolean containKey(String key)
	{
		return mMap.containsKey(key);
	}

	public synchronized Bitmap get(String key)
	{
		return mMap.get(key);
	}

	public synchronized void put(String key, Bitmap value)
	{
		mMap.put(key, value);
	}

	public synchronized int usedEntries()
	{
		return mMap.size();
	}

	public synchronized Collection<Map.Entry<String, Bitmap> > getAll()
	{
		return new ArrayList<Map.Entry<String, Bitmap> >(mMap.entrySet());
	}
}
